package com.learn.image.controller;

import com.learn.image.domain.ImageInfo;
import com.learn.image.service.ImageFileService;
import com.learn.image.service.impl.ImageWatermarkService;
import com.learn.image.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.Objects;

/**
 * 图片上传并添加水印接口
 *
 * @author: Administrator
 * @createTime: 2023/11/28 0028 17:13
 * @updateUser: Administrator
 * @updateTime: 2023/11/28 0028 17:13
 * @updateRemark: 修改内容
 * @version: v1.0
 */
@Slf4j
@RestController
@RequestMapping("/img")
public class ImageFileController<T> {

    @Resource
    private ImageFileService imageFileService;

    @Resource
    private ImageWatermarkService imageWatermarkService;

    /**
     * 文件上传并增加水印处理
     * @param txt
     * @param imgFile
     * @return
     */
    @GetMapping("/upload")
    public R<T> upload(@RequestParam("txt") String txt, @RequestParam("imgFile") MultipartFile imgFile) {
        return imageFileService.uploadImageFile(txt, imgFile);
    }


    /**
     * 文件上传并增加水印处理
     *
     * @param txt
     * @param imgFile
     * @return
     */
    @GetMapping("/water")
    public R imgWater(@RequestParam("txt") String txt, @RequestParam("imgFile") MultipartFile imgFile) {
        return imageFileService.addWatermark(txt,imgFile,null,String.valueOf(System.currentTimeMillis()));
    }

    /**
     * 文件上传并增加水印处理
     *
     * @param txt
     * @param imgFile
     * @return
     */
    @GetMapping("/file")
    public R imgWater(@RequestParam("imgFile") MultipartFile imgFile) {

        return new R(imgFile.getOriginalFilename());
    }

    @PostMapping(value = "/watermark")
    public ImageInfo watermarkTestTest( @RequestParam("file") MultipartFile image, @RequestParam("text") String text) {

        ImageInfo imgInfo = new ImageInfo();

        String uploadPath = "static/images/";  // 服务器上上传文件的相对路径
        String physicalUploadPath = Objects.requireNonNull(getClass().getClassLoader().getResource(uploadPath)).getPath();  // 服务器上上传文件的物理路径

        String imageUrl = imageFileService.uploadImage( image, uploadPath, physicalUploadPath );

        System.out.println("给图片添加水印文字开始...");

        // 给图片添加水印文字
        String waterMarkAddImageUrl = imageWatermarkService.markImage(text, physicalUploadPath + image.getOriginalFilename(), physicalUploadPath,uploadPath);
        System.out.println("给图片添加水印文字结束...");
        imgInfo.setImageUrl(imageUrl);
        imgInfo.setWaterMarkAddImageUrl(waterMarkAddImageUrl);
        return imgInfo;
    }
}
